﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Drawing;

namespace Citrix.XaAdminMobile.Util
{

    /// <summary>
    /// The return value from the Xenapp PS command GetXAApplicationIconByName is a Base64 encoded string. 
    /// To turn this back into an icon, one way is to decode the Base64 string and turn it into a bytearray,
    /// and then into an icon.
    /// 
    /// This class, IconConverter, provides help functions to accomplish the above.
    /// 
    /// </summary>
    
    public static class IconConverter
    {

        /// <summary>
        /// Decodes/converts a Base64 string into a regular bytearray and returns the bytearray. 
        /// The XA command GetXAApplicationIconByName will return a base64 encoded string of the icon of the application.
        /// </summary>
        
        public static byte[] Base64ToByteArray(String base64String)
        {
            byte[] decodedBase64String = Convert.FromBase64String(base64String);
            return decodedBase64String;
        }

        /// <summary>
        /// Converts a bytearray into an Icon and returns an Icon object. Turns bytearray into Image into Icon.
        /// </summary>

        public static Icon ByteArrayToIcon(byte[] byteArrayIn)
        {
            MemoryStream ms = new MemoryStream(byteArrayIn);
            Image returnImage = Image.FromStream(ms);

            return ImageToIcon(returnImage, 24, 24);
        }


        /// <summary>
        /// Helper function for ByteArrayToIcon which helps with the step of Image -> Icon.
        /// Returns an Icon.
        /// </summary>

        private static Icon ImageToIcon(Image img, float xDpi, float yDpi)
        {
            Bitmap bitmap = new Bitmap(img);
            bitmap.SetResolution(xDpi, yDpi);
            Icon icon = System.Drawing.Icon.FromHandle(bitmap.GetHicon());

            return icon;
        }
    }
}


